package com.dj.product.k2faas.jpa.sqlgenerator;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.util.JdbcConstants;
import com.dj.product.k2faas.jpa.dto.QueryArg;
import com.dj.product.k2faas.common.exception.K2Exception;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * Created by 丁建 on 2025/9/23 10:10
 *
 * @author 丁建
 */
@Slf4j
public abstract class AbstractMyBatisSqlGenerator implements SqlGenerator {
    private static final String TEMPLATE_OUTER = """
                    <?xml version="1.0" encoding="UTF-8"?>
                         <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
                         <mapper namespace="any">
                         	<select id="selectData">
                         		%s
                         	</select>
                         </mapper>""";

    @Override
    public String getQueryBasicSql(String template, QueryArg queryArg) {
        var fullTemplate = String.format(TEMPLATE_OUTER, template);
        //解析
        var xmlMapperBuilder = new XMLMapperBuilder(new ByteArrayInputStream(fullTemplate.getBytes(StandardCharsets.UTF_8)), new Configuration(), fullTemplate,
                                                    new HashMap<>());
        xmlMapperBuilder.parse();
        var mappedStatementNames = xmlMapperBuilder.getConfiguration().getMappedStatementNames();
        Assert.isTrue(!mappedStatementNames.isEmpty(), "XML中未解析到Sql配置。");

        var name = mappedStatementNames.stream().findFirst().orElseThrow(() -> new RuntimeException("XML中未解析到Sql的名称"));

        var mappedStatement = xmlMapperBuilder.getConfiguration().getMappedStatement(name);
        return mappedStatement.getBoundSql(queryArg.getArgs()).getSql();
    }

    protected String getConditionKeywordOfSql(String sql) {
        final String where = "where";
        final String and = "and";
        var whereTempSql = sql + " where 1=1 ";
        try {
            SQLUtils.parseStatements(whereTempSql, JdbcConstants.MYSQL);
            return where;
        } catch (Exception whereConditionParseException) {
            var andTempSql = sql + " and 1=1 ";
            try {
                SQLUtils.parseStatements(andTempSql, JdbcConstants.MYSQL);
                return and;
            } catch (Exception sqlParseException) {
                log.error(sqlParseException.getMessage(), sqlParseException);
                throw new K2Exception("SQL:" + sql + "解析出错:" + sqlParseException.getMessage());
            }
        }
    }
}
